﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SYcwpb.Access;
using SYcwpb.Helpers;
using SYcwpb.Views;
using SYcwpb.Models;
using SYcwpb.Commands;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Collections;
using SYcwpb.ViewModels.DataProvider;
using System.Data;
using SYcwpb.Controls;
using System.Windows;

namespace SYcwpb.ViewModels
{
    class CrossRoadEditorViewModel:ViewModelBase
    {
        private CrossingRoadObject _rowPara;
        private CrossRoadEditor _editorView;
        public CrossRoadEditorParameter _para;
        private DataTable Kilometersdt;
        double _outMiles = 0;
        double _inMiles = 0;
        private DataTable KilometersOutAndIndt;
        SqlDataLayer sql_Help = new SqlDataLayer();
        private int line = Convert.ToInt32(CONSTDATA.UserModel.Line);

        /// <summary>
        /// 夜班便乘回库的交路所用，记录最后一个驾驶车辆的时间
        /// </summary>
        public string LastTrainTime { get; set; }

        /// <summary>
        /// 便乘回去的最后一个车的车次号
        /// </summary>
        public string BCBackGarageTrainID { get; set; }

        private bool _cbox_Zhengxian;
        public bool Cbox_Zhengxian
        {
            get { return _cbox_Zhengxian; }
            set
            {
                _cbox_Zhengxian = value;

                OnPropertyChanged("Cbox_Zhengxian");
            }
        }

        private bool _cbox_ReBei;
        public bool Cbox_ReBei
        {
            get { return _cbox_ReBei; }
            set
            {
                _cbox_ReBei = value;

                OnPropertyChanged("Cbox_ReBei");
            }
        }

        private bool _cbox_DiaoChe;
        public bool Cbox_DiaoChe
        {
            get { return _cbox_DiaoChe; }
            set
            {
                _cbox_DiaoChe = value;

                OnPropertyChanged("Cbox_DiaoChe");
            }
        }

        private bool _cbox_ShiChe;
        public bool Cbox_ShiChe
        {
            get { return _cbox_ShiChe; }
            set
            {
                _cbox_ShiChe = value;

                OnPropertyChanged("Cbox_ShiChe");
            }
        }

        private bool _cbox_BeiYong;
        public bool Cbox_BeiYong
        {
            get { return _cbox_BeiYong; }
            set
            {
                _cbox_BeiYong = value;

                OnPropertyChanged("Cbox_BeiYong");
            }
        }

        private bool _cbox_MainDriver;
        public bool Cbox_MainDriver
        {
            get { return _cbox_MainDriver; }
            set
            {
                _cbox_MainDriver = value;

                OnPropertyChanged("Cbox_MainDriver");
            }
        }

        private bool _cbox_PaiBanYuan;
        public bool Cbox_PaiBanYuan
        {
            get { return _cbox_PaiBanYuan; }
            set
            {
                _cbox_PaiBanYuan = value;
                OnPropertyChanged("Cbox_PaiBanYuan");
            }
        }

        private bool _cbox_DuDao;
        public bool Cbox_DuDao
        {
            get { return _cbox_DuDao; }
            set
            {
                _cbox_DuDao = value;
                OnPropertyChanged("Cbox_DuDao");
            }
        }

        private bool _cbox_MonthBeiYong;
        public bool Cbox_MonthBeiYong
        {
            get { return _cbox_MonthBeiYong; }
            set
            {
                _cbox_MonthBeiYong = value;

                OnPropertyChanged("Cbox_MonthBeiYong");
            }
        }

        private bool _cbox_BianCheng;
        public bool Cbox_BianCheng
        {
            get { return _cbox_BianCheng; }
            set
            {
                _cbox_BianCheng = value;

                if (_cbox_BianCheng == true)
                    CBoBox_bc_Visibility = Visibility.Visible;
                else
                    CBoBox_bc_Visibility = Visibility.Collapsed;

                OnPropertyChanged("Cbox_BianCheng");
            }
        }

        private Visibility _cBoBox_bc_Visibility = Visibility.Collapsed;
        public Visibility CBoBox_bc_Visibility
        {
            get { return _cBoBox_bc_Visibility; }
            set
            {
                _cBoBox_bc_Visibility = value;

                OnPropertyChanged("CBoBox_bc_Visibility");
            }
        }


        private ICommand _cBClickCommand;
        public ICommand CBClickCommand
        {
            get
            {
                if (null == _cBClickCommand)
                    _cBClickCommand = new RelayCommands(para => this.CBClickCommand_Method(para));

                return _cBClickCommand;
            }
        }

        private List<string> _placeList;
        public List<string> PlaceList
        {
            get
            {
                if (line == 1)
                {
                    _placeList = new List<string>() { "车辆段","十三号街站","启工街站"};
                }
                else if (line == 2)
                {
                    _placeList = new List<string>() { "车辆段","全运路站","三台子站","青年大街站", "航空航天大学站", "蒲田路站" };
                }

                return _placeList;
            }
        }

        private string _attenPlace;
        public string AttenPlace
        {
            get { return _attenPlace; }
            set
            {
                if (value == _attenPlace)
                    return;
                _attenPlace = value;
                OnPropertyChanged("AttenPlace");
            }
        }

        private string _offPlace;
        public string OffPlace
        {
            get { return _offPlace; }
            set
            {
                if (value == _offPlace)
                    return;
                _offPlace = value;
                OnPropertyChanged("OffPlace");
            }
        }

        private string _miles;
        public string Miles
        {
            get { return _miles; }
            set
            {
                if (_miles == value)
                    return;
                _miles = value;
                OnPropertyChanged("Miles");
            }
        }

        private string _hours;
        public string Hours
        {
            get { return _hours; }
            set
            {
                if (_hours == value)
                    return;
                _hours = value;
                OnPropertyChanged("Hours");
            }
        }

        private string _note;
        public string Note
        {
            get { return _note; }
            set
            {
                if (_note == value)
                    return;
                _note = value;
                OnPropertyChanged("Note");
            }
        }

        public ObservableCollection<SmallTrain> _trainList = CrossingRoadViewModel.TrainList;
        public ObservableCollection<SmallTrain> TrainList
        {
            get { return _trainList; }
        }

        public ICommand _updateCrossRoadInfoCommand;
        public ICommand UpdateCrossRoadInfoCommand
        {
            get
            {
                if (null == _updateCrossRoadInfoCommand)
                    _updateCrossRoadInfoCommand = new RelayCommands(para => this.UpdateCrossRoadInfoCommand_Method());

                return _updateCrossRoadInfoCommand;
            }
        }

        public ICommand _confirmCommand;
        public ICommand ConfirmCommand
        {

            get {
                if (null == _confirmCommand)
                    _confirmCommand = new RelayCommands(para => this.ConfirmCommand_Method());

                return _confirmCommand;
            }
            
        }

        public ICommand _cancelCommand;
        public ICommand CancelCommand
        {

            get
            {
                if (null == _cancelCommand)
                    _cancelCommand = new RelayCommands(para => this.CancelCommand_Method());

                return _cancelCommand;
            }

        }

        public CrossRoadEditorViewModel(CrossRoadEditor editor, CrossingRoadObject row,CrossRoadEditorParameter para)
        {
            this._rowPara = row;
            this._editorView = editor;
            this._para = para;
            if ( null != _rowPara)
            {
                Init();
            }
        }

        /// <summary>
        /// 编辑的时候，需要将参数初始化至控件上
        /// </summary>
        private void Init()
        {
            AttenPlace = _rowPara.AttenPlace;
            OffPlace = _rowPara.OffPlace;

            SetRoadType(_rowPara.type);

            if (null != _rowPara.RepTrain && _rowPara.RepTrain.Contains("便"))
            {
                Cbox_BianCheng = true;
                if (_rowPara.RepTrain.Length == 8) // 通常便乘的文字形式为 "(便) + 5位车次号"  所以一共为8位
                    _editorView.SetBcOutTrain(_rowPara.RepTrain.Substring(3));
            }

            if (!string.IsNullOrEmpty(_rowPara.BCBackGarageTrainID))
            {
                _editorView.SetBcBcakTrain(_rowPara.BCBackGarageTrainID);
            }


            _editorView.SetTrain(_rowPara.StringCrossingRoad);

            _editorView.SetTime("ctl_planTime", _rowPara.PlanTime);
            _editorView.SetTime("ctl_trainTime", _rowPara.TrainTime);
            _editorView.SetTime("ctl_offTime", _rowPara.OffTime);

            Miles = _rowPara.Miles;
            Hours = _rowPara.Whours;
            Note = _rowPara.Notes;

            LastTrainTime = _rowPara.lastTrainTime;

            GetNewKilometersdt();
        }

        public void GetNewKilometersdt()
        {
            string str = "select * from NewKilometers where LineID='" + CONSTDATA.UserModel.Line + "'";
            Kilometersdt = sql_Help.SelectDt(str);
            string str2 = "select * from NewOutAndInKilometers where LineID='" + CONSTDATA.UserModel.Line + "'";
            KilometersOutAndIndt = sql_Help.SelectDt(str2);
            if (KilometersOutAndIndt.Rows.Count > 0)
            {
                _outMiles = int.Parse(KilometersOutAndIndt.Rows[0]["OutKilometers"].ToString());
                _inMiles = int.Parse(KilometersOutAndIndt.Rows[0]["InKilometers"].ToString());
            }
        }


        private void CBClickCommand_Method(object parameter)
        {
            string para = (string)parameter;

            SetRoadType(para);
        }

        private void UpdateCrossRoadInfoCommand_Method()
        {
            SmallTrain firstT = null;
            SmallTrain lastT = null;
            SmallTrain BcBackT = null;
            int beginT = -1;
            int planT = -1;
            int offT = -1;
            //出勤时间，发车时间获取
            if (Cbox_BianCheng)  //如果是便乘出勤的
            {
                firstT = _editorView.cBoBox_bcOut.SelectedItem as SmallTrain;
                if (null == firstT)
                {
                    MessageBoxHelper.ShowError("请先选择便乘车次！");
                    return;
                }
                else
                {
                   // beginT = firstT.BeginTime;
                    if (AttenPlace == "启工街站" || AttenPlace == "青年大街站")
                        beginT = firstT.TimeLeaveChangePoint;
                    else
                        beginT = firstT.BeginTime;
                    if (AttenPlace == "车辆段")
                        planT = beginT - Convert.ToInt32(_para._garageBCAhead) * 60;
                    else
                        planT = beginT - Convert.ToInt32(_para._normalAhead) * 60;
                }
            }
            else
            {
                firstT = _editorView.GetFirstTrain();
                if (null != firstT)
                {
                    string lastId = firstT.TrainID.Substring(3);

                    if (AttenPlace == "启工街站" || AttenPlace == "青年大街站")
                        beginT = firstT.TimeLeaveChangePoint;
                    else
                        beginT = firstT.BeginTime;

                    if ((line == 1 && lastId == "02") || (line == 2 && lastId == "01"))  //出库车
                    {
                        if (AttenPlace == "车辆段")
                            planT = beginT - Convert.ToInt32(_para._garageAhead) * 60;
                        else
                            planT = beginT - Convert.ToInt32(_para._normalAhead) * 60;
                    }
                    else
                    {
                        planT = beginT - Convert.ToInt32(_para._normalAhead) * 60;
                    }
                }
            }

            if (beginT != -1)
                _editorView.SetTime("ctl_trainTime", GlobalVariables.FormatTime(beginT.ToString()));  //发车时间
            if (planT != -1)
                _editorView.SetTime("ctl_planTime", GlobalVariables.FormatTime(planT.ToString()));   //出勤时间


            //退勤时间的更新
            BcBackT = _editorView.cBoBox_bcBack.SelectedItem as SmallTrain;
            lastT = _editorView.GetOffTrain();

            if (null == BcBackT)  //如果不是便乘回库的
            {
                if (null != lastT)
                {
                    if (OffPlace == "青年大街站" || OffPlace == "启工街站")
                    {
                        offT = lastT.TimeAtChangePoint + _para._normalDelay;
                    }
                    else if (OffPlace == "车辆段")
                        offT = lastT.EndTime + _para._garageDelay;
                    else
                        offT = lastT.EndTime + _para._normalDelay;
                }
                BCBackGarageTrainID = "";
            }
            else
            {
                BCBackGarageTrainID = BcBackT.TrainID;

                if (BcBackT.IsLastTrip)
                {
                    offT = BcBackT.EndTime + _para._garageDelay;
                    Note = string.Format("便 {0} 回库", BCBackGarageTrainID);
                }
                else
                {
                    offT = BcBackT.TimeAtChangePoint + _para._normalDelay;
                    Note = string.Format("便 {0} 退勤", BCBackGarageTrainID);
                }
            }

            //LastTrainTime = GlobalVariables.FormatTime(lastT.EndTime.ToString());
            if (offT != -1)
                _editorView.SetTime("ctl_offTime", GlobalVariables.FormatTime(offT.ToString()));

            if (offT == -1 || planT == -1)
            {
                try
                {
                    int seconds = Math.Abs(_editorView.GetTimeInt("ctl_offTime") - _editorView.GetTimeInt("ctl_planTime"));

                    Hours = Math.Round((double)(seconds) / 3600, 2).ToString();
                }
                catch (System.Exception ex)
                {
                	Hours = "0";
                    MessageBoxHelper.ShowError("工时统计异常，请检查无误后点击确认！");
                }

            }
            else
                Hours = Math.Round((double)(offT - planT) / 3600, 2).ToString();

            //Miles = _editorView.GetMiles();

            var trainList = _editorView.GetTrainList();
            double totalMiles = 0;
            for (int i = 0; i < trainList.Count; i++)
            {
                String startPlace = null, endPlace=null;
                if (i == 0)
                {
                    if (Cbox_BianCheng)
                    {
                        if (line == 1)
                            startPlace = "十三号街站";
                        else
                            startPlace = "全运路站";
                    }
                    else
                    {
                        startPlace = AttenPlace;
                    }
                }
                else
                {
                    startPlace = GetAttendOutPlace(trainList[i].StartPlace);
                }
                if(i==trainList.Count-1)
                {
                    if (_editorView.cBoBox_bcBack.SelectedIndex > 0)
                    {
                        if (line == 1)
                            endPlace = "十三号街站";
                        else
                            endPlace = "全运路站";
                    }
                    else
                    {
                        endPlace = OffPlace;
                    }
                }
                else
                {
                    endPlace = GetAttendOutPlace(trainList[i].EndPlace);
                }
                
                totalMiles += getline2miles2(startPlace, endPlace);
            }

            Miles = totalMiles.ToString();

        }

        private void UpdateTrainTimePlanTime()
        {

        }

        public double getline2miles2(String startP, String endP)
        {
            DataRow[] rows = Kilometersdt.Select("(StartStationID in " + GetPlace(startP) + " and EndStationID in " + GetPlace(endP) + ") or (StartStationID in " + GetPlace(endP) + " and EndStationID in " + GetPlace(startP) + ")");
            if (rows.Length > 0)
            {
                return double.Parse(rows[0]["Kilometers"].ToString());
            }
            else
            {
                return 0;
            }
        }
        public string GetAttendOutPlace(AttendOutPlace place)
        {
            string result = "";
            if (place == AttendOutPlace.Garage)
            {
                result = "车辆段";
            }
            else if (line == 1)
            {
                if (place == AttendOutPlace.MidSta)
                    result = "启工街站";
                else if (place == AttendOutPlace.LastSta)
                    result = "黎明广场站";
                else if (place == AttendOutPlace.FirSta)
                    result = "十三号街站";

            }
            else if (line == 2)
            {
                if (place == AttendOutPlace.MidSta)
                    result = "青年大街站";
                else if (place == AttendOutPlace.FirSta)
                    result = "全运路站";
                else if (place == AttendOutPlace.LastSta)
                    result = "蒲田路站";
                else if (place == AttendOutPlace.STZSta)
                    result = "三台子站";
                else if (place == AttendOutPlace.HKHSta)
                    result = "航空航天大学站";
                else if (place == AttendOutPlace.ZYYSta)
                    result = "中医药大学站";
            }

            if (result == "")
            {
                string err = "";
            }

            return result;
        }
        public String GetPlace(String place)
        {
            string result = "(";
            //if (place == AttendOutPlace.Garage)
            //{
            //    result = "车辆段";
            //}
            if (line == 1)
            {
                if (place == "启工街站")
                    result += "'10'";
                else if (place == "黎明广场站")
                    result += "'22'";
                else if (place == "十三号街站")
                    result += "'1'";
                else if (place == "车辆段")
                    result += "'66','67'";

            }
            else if (line == 2)
            {
                if (place == "青年大街站")
                    result += "'10'";
                else if (place == "全运路站")
                    result += "'1'";
                else if (place == "蒲田路站")
                    result += "'26'";
                else if (place == "三台子站")
                    result += "'19'";
                else if (place == "航空航天大学站")
                    result += "'22'";
                else if (place == "车辆段")
                    result += "'66','67'";
            }
            result += ")";

            return result;
        }
        private void ConfirmCommand_Method()
        {
            CrossingRoadModel roadModel = new CrossingRoadModel();

            roadModel.RepTrain = _editorView.GetRepTrain();

            if (Cbox_BianCheng) 
            {
                if (string.IsNullOrEmpty(roadModel.RepTrain))//便乘的交路不允许没有车次
                {
                    MessageBoxHelper.ShowError("便乘交路首车次不能为空");
                    return;
                }
                roadModel.RepTrain = _editorView.GetRepTrainByBC();
                roadModel.RepTrain = "(便)" + roadModel.RepTrain;
            }

            roadModel.AttenPlace = AttenPlace;
            roadModel.OffPlace = OffPlace;

            roadModel.StringCrossingRoad = _editorView.GetTrainList(AttenPlace, OffPlace);

            roadModel.PlanTime = _editorView.GetTime("ctl_planTime");
            roadModel.TrainTime = _editorView.GetTime("ctl_trainTime");
            roadModel.OffTime = _editorView.GetTime("ctl_offTime");

            SmallTrain offTrain = _editorView.GetOffTrain();
            if (null != offTrain)
                roadModel.OffTrain = _editorView.GetOffTrain().TrainID;

            roadModel.Miles = Miles;
            roadModel.Whours = Hours;
            roadModel.Notes = Note;

            if (roadModel.AttenPlace == "启工街站" || roadModel.AttenPlace == "青年大街站")
                roadModel.midStart = 1;
            if (roadModel.OffPlace == "启工街站" || roadModel.OffPlace == "青年大街站")
                roadModel.midOut = 1;

            roadModel.type = GetRoadType();

            SmallTrain BcBackT = _editorView.cBoBox_bcBack.SelectedItem as SmallTrain;
            SmallTrain lastT = _editorView.GetOffTrain();

            if (null != BcBackT)
            {
                roadModel.BCBackGarageTrainID = BcBackT.TrainID;
                //roadModel.OffTime = GlobalVariables.FormatTime(BcBackT.EndTime.ToString());
                roadModel.OffTrain = BcBackT.TrainID;
            }
            else
            {
                roadModel.BCBackGarageTrainID = "";
            }
            if (null != lastT)
            {
                roadModel.lastTrainTime = GlobalVariables.FormatTime(lastT.EndTime.ToString());
            }
            else
            {
                roadModel.lastTrainTime = "";
            }

            _editorView.OnCommited(new CrossingRoadObject(roadModel));

            this.Close();
        }

        private string GetRoadType()
        {
            string type = "";

            if (Cbox_ReBei)
                type = "热备";
            else if (Cbox_DiaoChe)
                type = "调车";
            else if (Cbox_ShiChe)
                type = "试车线";
            else if (Cbox_BeiYong)
                type = "备班";
            else if (Cbox_MonthBeiYong)
                type = "月备班";
            else if (Cbox_MainDriver)
                type = "司机长";
            else if (Cbox_DuDao)
                type = "督导员";
            else if (Cbox_PaiBanYuan)
                type = "派班员";

            return type;
        }

        private void SetRoadType(string para)
        {
            Cbox_Zhengxian = false;
            Cbox_ReBei = false;
            Cbox_DiaoChe = false;
            Cbox_ShiChe = false;
            Cbox_BeiYong = false;
            Cbox_MonthBeiYong = false;
            Cbox_MainDriver = false;

            switch (para)
            {
                case "":
                    Cbox_Zhengxian = true;
                    break;
                case "热备":
                    Cbox_ReBei = true;
                    break;
                case "调车":
                    Cbox_DiaoChe = true;
                    break;
                case "试车线":
                    Cbox_ShiChe = true;
                    break;
                case "备班":
                    Cbox_BeiYong = true;
                    break;
                case "月备班":
                    Cbox_MonthBeiYong = true;
                    break;
                case "司机长":
                    Cbox_MainDriver = true;
                    break;
                case "督导员":
                    Cbox_DuDao = true;
                    break;
                case "派班员":
                    Cbox_PaiBanYuan = true;
                    break;
            }
        }

        private void CancelCommand_Method()
        {
            this.Close();
        }

        private void Close()
        {
            _editorView.Close();
        }
    }
}
